package com.infoguia;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.infoguia.db.InfoguiaDao;
import com.infoguia.to.*;
import com.infoguia.util.Constants;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MainCategories extends ListActivity {

	private int ACTIVITY_RESULT_LIST = 2;
	private InfoguiaDao dao;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.principal_categories);
		
		this.loadCategoriasPrincipales();
		this.goHome();
	}

	private void loadCategoriasPrincipales() {

		List<CategoryTo> principales;
		String[] results;
		int i = 0;

		if (dao == null) {
			dao = new InfoguiaDao(MainCategories.this);
			dao.open();
		}

		principales = dao.getMainCategories();

		results = new String[principales.size()];
		for (CategoryTo cat : principales) {
			results[i++] = cat.getName();
		}

		String[] from = new String[] { "row_0", "row_1"};
		int[] to = new int[] { R.id.textCR, R.id.idElement};
		
		List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();

		for (CategoryTo rec : principales){
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("row_0", rec.getName());
			map.put("row_1", String.valueOf(rec.getId()));		
			fillMaps.add(map);
		}		
		
		setListAdapter(new SimpleAdapter(this, fillMaps, R.layout.cr_row, from,
				to));
		
		getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapter, View view,
					int position, long arg) {
				
				TextView textView = (TextView) view.findViewById(R.id.idElement);							
				Intent i = new Intent(MainCategories.this, ResultList.class);
				i.putExtra(Constants.ID, Long.parseLong(textView.getText().toString()));
				i.putExtra("SEARCH_REC", Long.parseLong("1"));
				startActivityForResult(i, ACTIVITY_RESULT_LIST);
			}
		});
		
		dao.close();
	}
	
	public void goHome() {

		ImageView home = (ImageView) findViewById(R.id.home);

		home.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(MainCategories.this, StartActivity.class);
				startActivityForResult(i, 1);
			}
		});

	}
}